package com.ideal.manage.esms.util;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class IntegrationUtils {
    public interface IntegrationFunction {
        public double fun(int idx, double x);
    }


    public static List<Double> sumReduceCount(List<Double> fifteenList, int reduceCount) {
        double sum = 0;
        List<Double> r = new ArrayList<>();
        for (int i = 0; i < fifteenList.size(); i++) {
            sum += fifteenList.get(i);
            if ((i + 1) % reduceCount == 0) {
                r.add(new BigDecimal(sum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        }
        if (fifteenList.size() % 2 != 0) {
            r.add(new BigDecimal(sum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        }
        return r;
    }


    public static double simpsonRule(double upper, double lower, int n, IntegrationFunction df) {
        if (n == 0) {
            return 0;
        }
        double result = 0;

        double unit = (upper - lower) / n;
        double factor1 = unit / 3;
        double[] x = new double[n];

        for (int i = 0; i < x.length; i++) {
            x[i] = lower + unit * i;
        }
        for (int i = 0; i < x.length; i++) {
            if (i == 0 || i == x.length - 1) {
                result += df.fun(i, x[i]);
            } else if (i % 2 == 0) { // if i is even num.
                result += 2 * df.fun(i, x[i]);
            } else { // if i is odd num.
                result += 4 * df.fun(i, x[i]);
            }
        }

        result *= factor1;
        return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
